package com.sdr.ddpushtcp;


import android.Manifest;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.text.TextUtils;
import android.widget.Toast;

import com.sdr.ddpushtcp.service.OnlineService;
import com.sdr.ddpushtcp.util.Params;
import com.sdr.ddpushtcp.util.Util;

import org.apache.cordova.CallbackContext;
import org.apache.cordova.CordovaPlugin;
import org.ddpush.im.v1.client.appserver.Pusher;
import org.json.JSONArray;
import org.json.JSONException;

/**
 * Created by homelajiang on 2016/8/2 0002.
 */
public class DDPushTCPManager extends CordovaPlugin {

    public static boolean Inited;

    @Override
    public boolean execute(String action, JSONArray args, final CallbackContext callbackContext) throws JSONException {
        if (TextUtils.isEmpty(action)) {
            return false;
        }

        if (action.equals("test")) {
            Toast.makeText(cordova.getActivity(), "just a Test", Toast.LENGTH_SHORT).show();
            return true;
        }
        //初始化 端口号，ip，用户名等
        if (action.equals("initialize")) {//ip server_port local_port
            cordova.requestPermission(this,0, Manifest.permission.ACCESS_NETWORK_STATE);
            SharedPreferences account = cordova.getActivity().getSharedPreferences(Params.DEFAULT_PRE_NAME, Context.MODE_PRIVATE);
            SharedPreferences.Editor editor = account.edit();
            editor.putString(Params.USER_ID, args.getString(0));
            editor.putString(Params.SERVER_IP, args.getString(1));
            editor.putString(Params.SERVER_PORT, args.getString(2));
            editor.putString(Params.PUSH_PORT, args.getString(3));
            editor.putString(Params.SENT_PKGS, "0");
            editor.putString(Params.RECEIVE_PKGS, "0");
            editor.apply();
            Intent startSrv = new Intent(cordova.getActivity(), OnlineService.class);
            startSrv.putExtra("CMD", "RESET");
            cordova.getActivity().startService(startSrv);
            return true;
        }
        //发送通用推送信息
        if (action.equals("commonMsg")) {
            if (!Inited) {
                if (callbackContext != null) {
                    callbackContext.error("推送服务未初始化");
                    return true;
                }
            }
            SharedPreferences account = cordova.getActivity().getSharedPreferences(Params.DEFAULT_PRE_NAME, Context.MODE_PRIVATE);
            final String serverIp = account.getString(Params.SERVER_IP, "");
            String pushPort = account.getString(Params.PUSH_PORT, "");

            if (TextUtils.isEmpty(serverIp)) {
                callbackMsg(callbackContext,"服务器ip为空",false);
                return true;
            }
            final int port;
            try {
                port = Integer.parseInt(pushPort);
            } catch (Exception e) {
                callbackMsg(callbackContext,"推送端口格式错误",false);
                return true;
            }
            final byte[] uuid;
            try {
                uuid = Util.md5Byte(args.getString(0));
            } catch (Exception e) {
                callbackMsg(callbackContext,"获取用户唯一识别号失败",false);
                return true;
            }

            cordova.getThreadPool().execute(new Runnable() {
                @Override
                public void run() {
                    Pusher pusher = null;
                    try {
                        boolean result;
                        pusher = new Pusher(serverIp, port, 1000 * 5);
                        result = pusher.push0x10Message(uuid);
                        if (result) {
                            callbackMsg(callbackContext,"通用信息发送成功",true);
                        } else {
                            callbackMsg(callbackContext,"发送失败！格式有误",false);
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                        callbackMsg(callbackContext,"发送失败！\" + e.getMessage()",false);
                    } finally {
                        if (pusher != null) {
                            try {
                                pusher.close();
                            } catch (Exception e) {
                            }
                        }
                    }
                }
            });

            return true;
        }
        //发送分类推送信息
        if (action.equals("sortMsg")) {
            if (!Inited) {
                if (callbackContext != null) {
                    callbackContext.error("推送服务未初始化");
                    return true;
                }
            }
            SharedPreferences account = cordova.getActivity().getSharedPreferences(Params.DEFAULT_PRE_NAME, Context.MODE_PRIVATE);
            final String serverIp = account.getString(Params.SERVER_IP, "");
            String pushPort = account.getString(Params.PUSH_PORT, "");

            if (TextUtils.isEmpty(serverIp)) {
                callbackMsg(callbackContext,"服务器ip为空",false);
                return true;
            }
            final int port;
            try {
                port = Integer.parseInt(pushPort);
            } catch (Exception e) {
                callbackMsg(callbackContext,"推送端口格式错误",false);
                return true;
            }
            final byte[] uuid;
            try {
                uuid = Util.md5Byte(args.getString(0));
            } catch (Exception e) {
                callbackMsg(callbackContext,"获取用户唯一识别号失败",false);
                return true;
            }

            final long msg;
            try{
                msg = args.getLong(1);
            }catch(Exception e){
                callbackMsg(callbackContext,"数字格式错误",false);
                return true;
            }

            if(msg==0){
                callbackMsg(callbackContext,"数字必须非零",false);
                return true;
            }

            cordova.getThreadPool().execute(new Runnable() {
                @Override
                public void run() {
                    Pusher pusher = null;
                    try {
                        boolean result;
                        pusher = new Pusher(serverIp, port, 1000 * 5);
                        result = pusher.push0x11Message(uuid,msg);
                        if (result) {
                            callbackMsg(callbackContext,"分类信息发送成功",true);
                        } else {
                            callbackMsg(callbackContext,"发送失败！格式有误",false);
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                        callbackMsg(callbackContext,"发送失败！\" + e.getMessage()",false);
                    } finally {
                        if (pusher != null) {
                            try {
                                pusher.close();
                            } catch (Exception e) {
                            }
                        }
                    }
                }
            });
            return true;
        }
        //发送自定义推送信息
        if (action.equals("customMsg")) {
            if (!Inited) {
                if (callbackContext != null) {
                    callbackContext.error("推送服务未初始化");
                    return true;
                }
            }
            SharedPreferences account = cordova.getActivity().getSharedPreferences(Params.DEFAULT_PRE_NAME, Context.MODE_PRIVATE);
            final String serverIp = account.getString(Params.SERVER_IP, "");
            String pushPort = account.getString(Params.PUSH_PORT, "");

            if (TextUtils.isEmpty(serverIp)) {
                callbackMsg(callbackContext,"服务器ip为空",false);
                return true;
            }
            final int port;
            try {
                port = Integer.parseInt(pushPort);
            } catch (Exception e) {
                callbackMsg(callbackContext,"推送端口格式错误",false);
                return true;
            }
            final byte[] uuid;
            try {
                uuid = Util.md5Byte(args.getString(0));
            } catch (Exception e) {
                callbackMsg(callbackContext,"获取用户唯一识别号失败",false);
                return true;
            }

            final byte[] msg;
            try{
                msg = args.getString(1).getBytes("UTF-8");
            }catch(Exception e){
                callbackMsg(callbackContext,"请输入信息",false);
                return true;
            }

            cordova.getThreadPool().execute(new Runnable() {
                @Override
                public void run() {
                    Pusher pusher = null;
                    try {
                        boolean result;
                        pusher = new Pusher(serverIp, port, 1000 * 5);
                        result = pusher.push0x20Message(uuid,msg);
                        if (result) {
                            callbackMsg(callbackContext,"自定义信息发送成功",true);
                        } else {
                            callbackMsg(callbackContext,"发送失败！格式有误",false);
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                        callbackMsg(callbackContext,"发送失败！\" + e.getMessage()",false);
                    } finally {
                        if (pusher != null) {
                            try {
                                pusher.close();
                            } catch (Exception e) {
                            }
                        }
                    }
                }
            });
            return true;
        }
        return super.execute(action, args, callbackContext);
    }

    public void callbackMsg(CallbackContext callbackContext ,String msg,boolean successed){
        if(successed && callbackContext!=null){
            callbackContext.success(msg);
        }
        if(!successed && callbackContext!=null){
            callbackContext.error(msg);
        }
    }
}
